package cnt5106.p2p.common;

import java.net.SocketAddress;
import java.util.Arrays;
import java.util.Vector;

import cnt5106.p2p.common.protocol.Message;

public class Utils {

	public static byte[] convertIntToByteArray(int value) {
		byte[] result = new byte[4];
		for (int i = 3; i >= 0; --i) {
			result[i] = (byte) (value & 0xFF);
			value >>= 8;
		}
		return result;
	}
	
	public static int convertByteArrayToInt(byte[] array) {
		if (array.length != 4) return 0;
		int result = 0;
		for (int i = 0; i != 4; ++i) {
			result <<= 8;
			result |= (array[i] & 0xFF);
		}
		return result;
	}
	
	public static void appendArrayToVector(Vector<Byte> vector, byte[] array) {
		vector.addAll(Arrays.asList(boxByteArray(array)));
	}
	
	public static byte[] unboxByteArray(Byte[] array) {
		byte[] result = new byte[array.length];
		for (int i = 0; i != array.length; ++i) {
			result[i] = array[i];
		}
		return result;
	}
	
	public static Byte[] boxByteArray(byte[] array) {
		Byte[] result = new Byte[array.length];
		for (int i = 0; i != array.length; ++i) {
			result[i] = array[i];
		}
		return result;
	}
	
	public static String logMessage(String name, SocketAddress local, boolean isSent, SocketAddress remote, Message msg) {
		return "[" + name + ": " + local + "]\n" 
			+ (isSent ? "Sent to " : "Received from") + remote + ": " + msg;
	}
}
